package ar.edu.itba.pod.legajo47573;

import java.rmi.NotBoundException;
import java.rmi.RemoteException;

import org.joda.time.Duration;

import ar.edu.itba.node.NodeInformation;
import ar.edu.itba.pod.time.TimeMapper;
import ar.edu.itba.pod.time.TimeMappers;

public class Main implements Runnable {

	private static String type;
	private static String id;
	private static String host;
	private static int port;
	private static String remoteHost;
	private static int remotePort;

	public static void main(String[] args) {
		type = args[0];
		id = args[1];
		host = args[2];
		port = Integer.valueOf(args[3]);
		if(!type.equals("create")){
			remoteHost = args[4];
			remotePort = Integer.valueOf(args[5]);
		}
		new Main().run();
	}

	@Override
	public void run() {

		NodeInformation info = new NodeInformation(host, port, id);
		TimeMapper timeMapper = TimeMappers.oneSecondEach(Duration.standardHours(6));

		final MyNode node = new MyNode(info, timeMapper);
		Thread thread = new Thread(node);
		thread.start();

		if(type.equals("create")){
			try {
				node.getCluster().createGroup();
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		else if(type.equals("connect")){
			try {
				node.getCluster().connectToGroup(remoteHost, remotePort);
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NotBoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
